package org.ichow.scenegame.view
{
	import flash.display.DisplayObjectContainer;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import org.ichow.debug.Log;
	import org.ichow.scenegame.controller.ScoreEffectCommand;
	import org.ichow.scenegame.core.MovieManager;
	import org.ichow.scenegame.events.SceneEvent;
	import org.ichow.scenegame.model.MovieProxy;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	/**
	 * ...
	 * @author M.ichow
	 */
	public class MovieMediator extends Mediator
	{
		public static const NAME:String = "MovieMediator";
		static public const SCORE_EFFECT:String = "scoreChange";
		
		private var _currentMovie:MovieClip;
		private var _timer:Timer;
		
		public function MovieMediator( app:MovieManager )
		{
			super( NAME , app );
			_timer = new Timer( 500 , 0 );
			_timer.addEventListener( TimerEvent.TIMER , onTimer );
		}
		
		private function onTimer( e:TimerEvent ):void
		{
			if ( _currentMovie )
			{
				if ( _currentMovie.currentFrame == _currentMovie.totalFrames )
				{
					_timer.reset();
					sendNotification( SceneEvent.MOVIE_END );
				}
			}
		}
		
		override public function onRegister():void
		{
			super.onRegister();
			//注册加载代理
			facade.registerProxy( new MovieProxy() );
			//注册分数动画方法
			facade.registerCommand( SCORE_EFFECT , ScoreEffectCommand );
		}
		
		override public function listNotificationInterests():Array
		{
			return [ SceneEvent.MOVIE_LOADED , SceneEvent.MOVIE_END , SceneEvent.ADD_TO_SCENE ];
		}
		
		override public function handleNotification( notification:INotification ):void
		{
			super.handleNotification( notification );
			switch ( notification.getName() )
			{
				case SceneEvent.ADD_TO_SCENE: 
					var scene:DisplayObjectContainer = notification.getBody() as DisplayObjectContainer;
					scene.addChildAt( movie , 0 );
					Log.trace( "++添加动画层" );
					break;
				case SceneEvent.MOVIE_LOADED: 
					// remove
					if ( _currentMovie && movie.contains( _currentMovie ) )
						movie.removeChild( _currentMovie );
					// add listener
					_currentMovie = notification.getBody() as MovieClip;
					// play movie
					movie.addChild( _currentMovie );
					if ( !_timer.running )
					{
						_timer.start();
					}
					Log.trace( ">>播放动画" );
					break;
				case SceneEvent.MOVIE_END: 
					_currentMovie.stop();
					if ( _currentMovie.currentFrame != _currentMovie.totalFrames )
						_currentMovie.gotoAndStop( _currentMovie.totalFrames );
					Log.trace( "播放结束<<" );
					break;
			}
		}
		
		protected function get movie():MovieManager
		{
			return viewComponent as MovieManager;
		}
	
	}

}